<?php
/**
 * Created by JetBrains PhpStorm.
 * User: geminiblue
 * Date: 13-10-25
 * Time: 下午5:52
 * To change this template use File | Settings | File Templates.
 */
Yii::import('application.components.Snoopy');

class HttpLib
{
    /**
     * @param $url
     * @param $post_data
     * @return mixed|null
     */
    public static function post($url,$post_data,$back_host='back_host')
    {
        if(!$url)
            return (object)array('errorMsg'=>'url can not be blank','success'=>0);
        $post_data['_ts'] = time();
        $post_data        = array_merge($post_data,Yii::app()->params['globalParams']);
        $sdata            = array();
        foreach($post_data as $key=>$value)
        {
            $sdata[$key] = is_string($value)?trim($value):$value;
        }
        try
        {
            $_snoopy               = new Snoopy();
            $_snoopy->read_timeout = 10;
            $data                  = null;
            $furl                  = Yii::app()->params[$back_host].$url;
            $begin_time            = microtime(true);
            $_snoopy->submit($furl,$sdata);
            $spent_time = intval((microtime(true) - $begin_time)*1000);
            if(YII_DEBUG)
                Yii::log(self::getRemoteIp().' '.MOBILEOS.' '.APPVERSION.' request '.$furl.' params are '.json_encode($sdata).' and the result is '.$_snoopy->results.' spent time '.$spent_time.' ms',CLogger::LEVEL_INFO,'api.info.log');
            else
                Yii::log(MOBILEOS.' '.APPVERSION.' request '.$furl.' spent time '.$spent_time.' ms',CLogger::LEVEL_INFO,'api.info.log');
            if($_snoopy->results!='')
            {
                json_decode($_snoopy->results);
                switch(json_last_error())
                {
                    case JSON_ERROR_NONE:
                        if(!json_decode($_snoopy->results)->success)
                        {
                            if(YII_DEBUG)
                                Yii::log(self::getRemoteIp().' '.MOBILEOS.' '.APPVERSION.' request '.$furl.' params are '.json_encode($sdata).' return failure '.$_snoopy->results,CLogger::LEVEL_WARNING,'api.warning.log');
                            else
                                Yii::log(self::getRemoteIp().' '.MOBILEOS.' '.APPVERSION.' request '.$furl.' return failure '.$_snoopy->results,CLogger::LEVEL_WARNING,'api.warning.log');
                        }
                        return CJSON::decode($_snoopy->results,false);
                    case JSON_ERROR_DEPTH:
                        return self::getError('Maximum stack depth exceeded');
                    case JSON_ERROR_STATE_MISMATCH:
                        return self::getError('Underflow or the modes mismatch');
                    case JSON_ERROR_CTRL_CHAR:
                        return self::getError('Unexpected control character found');
                    case JSON_ERROR_SYNTAX:
                        return self::getError('inteface returns not  a json data');
                    case JSON_ERROR_UTF8:
                        return self::getError('Malformed UTF-8 characters, possibly incorrectly encoded');
                    default:
                        return self::getError('Unknown error');
                }
            }
            else
            {
                if(YII_DEBUG)
                    Yii::log(self::getRemoteIp().' '.MOBILEOS.' '.APPVERSION.' request '.$url.' has error ,params are '.json_encode($sdata),CLogger::LEVEL_ERROR,'api.error.request');
                else
                    Yii::log(self::getRemoteIp().' '.MOBILEOS.' '.APPVERSION.' request '.$url.' has error',CLogger::LEVEL_ERROR,'api.error.request');
                return (object)array('errorMsg'=>Yii::app()->params['errorMsg'],'success'=>0);
            }

            return $data;
        }
        catch (Exception $ex)
        {
            return (object)array('errorMsg'=>Yii::app()->params['errorMsg'],'success'=>0);
        }
    }
    /**
     * @param $url
     * @param string $post_data
     * @return mixed|null
     */
    public static function get($url,$post_data='',$host='back_host')
    {
        if(!$url)
            return (object)array('errorMsg'=>'url can not be blank','success'=>0);
        $str = '';
        if(is_array($post_data))
        {
            $post_data['_ts'] = time();
            $post_data        = array_merge($post_data,Yii::app()->params['globalParams']);
            foreach($post_data as $key=>$value)
            {
                $str.='&'.$key.'='.urlencode(trim($value));
            }
        }
        try
        {
            $_snoopy               = new Snoopy();
            $_snoopy->read_timeout = 10;
            $url                   = Yii::app()->params[$host].$url;
            $furl                  = $url.'?'.substr($str,1,strlen($str));
            $begin_time            = microtime(true);
            $_snoopy->fetch($furl);
            $spent_time = intval((microtime(true) - $begin_time)*1000);
            if(YII_DEBUG)
                Yii::log(self::getRemoteIp().' '.MOBILEOS.' '.APPVERSION.' request '.$furl.' the result is '.$_snoopy->results.' spent time '.$spent_time.' ms',CLogger::LEVEL_INFO,'api.info.log');
            else
                Yii::log(MOBILEOS.' '.APPVERSION.' request '.$furl.' spent time '.$spent_time.' ms',CLogger::LEVEL_INFO,'api.info.log');
            if($_snoopy->results!='')
            {
                json_decode($_snoopy->results);
                switch(json_last_error())
                {
                    case JSON_ERROR_NONE:
                        if(!json_decode($_snoopy->results)->success)
                        {
                            Yii::log(self::getRemoteIp().' '.MOBILEOS.' '.APPVERSION.' request '.$furl.' return failure '.$_snoopy->results,CLogger::LEVEL_WARNING,'api.warning.log');
                        }
                        return CJSON::decode($_snoopy->results,false);
                    case JSON_ERROR_DEPTH:
                        return self::getError('Maximum stack depth exceeded');
                    case JSON_ERROR_STATE_MISMATCH:
                        return self::getError('Underflow or the modes mismatch');
                    case JSON_ERROR_CTRL_CHAR:
                        return self::getError('Unexpected control character found');
                    case JSON_ERROR_SYNTAX:
                        return self::getError('inteface returns not  a json data');
                    case JSON_ERROR_UTF8:
                        return self::getError('Malformed UTF-8 characters, possibly incorrectly encoded');
                    default:
                        return self::getError('Unknown error');
                }

            }
            else
            {
                Yii::log(self::getRemoteIp().' '.MOBILEOS.' '.APPVERSION.' request '.$furl.' has error >',CLogger::LEVEL_ERROR,'api.error.request');
                return (object)array('errorMsg'=>Yii::app()->params['errorMsg'],'success'=>0);
            }

        }catch (Exception $ex)
        {
           return (object)array('errorMsg'=>Yii::app()->params['errorMsg'],'success'=>0);
        }
    }
    /**
     * @return mixed
     */
    public static function getRemoteIp()
    {
        $unknown = 'unknown';
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)) {
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)) {
                $ip = $_SERVER['REMOTE_ADDR'];
        }
        /*
                处理多层代理的情况
                或者使用正则方式：$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;
        */
        if (false !== strpos($ip, ',')) $ip = reset(explode(',', $ip));
        return $ip;
    }

    public static function getError($errorMsg)
    {
        if(SITEMODE !== 'DEVELOP')
            $errorMsg = Yii::app()->params['errorMsg'];
        return (object)array('errorMsg'=>$errorMsg,'success'=>0);
    }
}
